﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using log4net;

namespace ConsoleOldToNew
{
    //------------------------------------------------------------------------------
    // ClassName:    SocketClient
    // Function :    Socket客户端操作类
    //                   
    // Edit Date:    2008-08-7
    // author   :    严江华
    // version  :    v 1.0.0
    //------------------------------------------------------------------------------ 

    /// <summary>
    /// Socket客户端操作类
    /// </summary>
     class SocketClient
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(SocketClient));

        private IPAddress ip;
        private Socket s;
        /// <summary>
        /// 获取或设置Socket
        /// </summary>
        public Socket S
        {
            get { return s; }
            set { s = value; }
        }
        private IPEndPoint point;


        #region 公共方法
        /// <summary>
        /// 数据传输连接
        /// </summary>
        /// <param name="hostName"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public bool Data_Trans_Conn(string hostName, int port)
        {
            lock (this)
            {
                return TCP_EstablishConn(hostName, port);
            }
        }

        /// <summary>
        /// 数据传输关闭
        /// </summary>
        /// <returns></returns>
        public bool Data_Trans_Close()
        {
            return TCP_ReleaseConn();
        }

        /// <summary>
        /// 数据发送
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="sendTimeout"></param>
        /// <returns></returns>
        public bool Data_Send(byte[] bt, int sendTimeout)
        {
            lock (this)
            {
                return SendData(bt, sendTimeout);
            }
        }

        /// <summary>
        /// 数据接受
        /// </summary>
        /// <param name="receiveTimeout"></param>
        /// <returns></returns>
        public byte[] Data_Receive(int receiveTimeout)
        {
            //lock (this)
            //{
                return ReceiveData(receiveTimeout);
            //}
        }

        #endregion


        #region 数据发送与接收
        /// <summary>
        /// 数据传输连接
        /// </summary>
        /// <param name="hostIP"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        private bool TCP_EstablishConn(string hostIP, int port)
        {
            try
            {
                if (s == null || !s.Connected)
                {
                    s = new Socket(AddressFamily.InterNetwork,
                 SocketType.Stream,
                 ProtocolType.Tcp);

                   
                    ip = IPAddress.Parse(hostIP);
                    point = new IPEndPoint(ip, port);
                    s.Connect(point);
                }
               
                return true;
            }
            catch (Exception ex)
            {
                Log.Error( ex );
                Thread.Sleep(10000);
                return false;
            }

        }

        /// <summary>
        /// 关闭数据传输连接
        /// </summary>
        /// <returns></returns>
        private bool TCP_ReleaseConn()
        {
            
                if (s != null && s.Connected == true)
                {
                    s.Close();

                }
                //else
                //{
                //    return false;
                //}
           

            return true;
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="sendTimeout"></param>
        /// <returns></returns>
        private bool SendData(byte[] bt, int sendTimeout)
        {
            
                if (s != null && s.Connected == true)
                {
                    s.SendTimeout = sendTimeout;
                    if (s.Send(bt) > 0)
                    {
                        return true;
                    }
                }
           
            return false;
        }


        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="receiveTimeout"></param>
        /// <returns></returns>
        private byte[] ReceiveData(int receiveTimeout)
        {
            byte[] btSub = null;
            if (s != null && s.Connected == true)
            {
                //if (receiveTimeout != 0)//
                //{
                    s.ReceiveTimeout = receiveTimeout;
                //}
                byte[] bt = new byte[1024];

                int num = 0;
              
                if ((num = s.Receive(bt)) > 0)
                {
                    btSub = new byte[num];
                    for (int i = 0; i < num; i++)
                    {
                        btSub[i] = bt[i];
                    }

                }

            }

            return btSub;

        }
        #endregion
    }
}
